<template>
  <div class="inventory-detail detail-bg">
    <div class="header">
      <h5>盘点详情({{ taskNum }}, {{ getStatusText(inventoryTaskDetail?.status) }})</h5>
      <el-button @click="goBack" type="text" class="back-btn">
        <i class="el-icon-arrow-left"></i> 返回
      </el-button>
    </div>
    
    <!-- 基本信息 -->
    <el-card class="info-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点任务名称：</span>
            <span class="value">{{ inventoryTaskDetail?.taskName || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点仓库：</span>
            <span class="value">{{ inventoryTaskDetail?.stockName || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点库区：</span>
            <span class="value">{{ getWarehouseNames() || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点日期：</span>
            <span class="value">{{ formatDate(inventoryTaskDetail?.takeDate) || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点人：</span>
            <span class="value">{{ inventoryTaskDetail?.userName || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">盘点备注：</span>
            <span class="value">{{ inventoryTaskDetail?.note || '-' }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 盘点明细 -->
    <el-card class="detail-card" shadow="never" style="margin-top: 20px;">
      <template #header>
        <span class="card-header">盘点物品(共{{count}})
          <el-button type="primary" size="small" @click="switchToGroup" style="margin-left: 10px;">切换分组展示</el-button>
        </span>
      </template>
      
      <el-table 
        :data="currentPageData" 
        border 
        size="small"
        :empty-text="'暂无盘点明细数据'"
      >
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column prop="code" label="物品编码" width="120" />
        <el-table-column prop="category" label="物品品类" width="100" />
        <el-table-column prop="name" label="物品名称" width="150" />
        <el-table-column prop="spec" label="物品规格" width="120" />
        <el-table-column prop="unit" label="计量单位" width="80" />
        <el-table-column prop="batchNo" label="批次号" width="120" />
        <el-table-column prop="validTime" label="有效期" width="120" />
        <el-table-column prop="locationName" label="货位" width="100" />
        <el-table-column prop="systemQty" label="库存数量" width="90" />
        <el-table-column prop="actualQty" label="实盘数量" width="90" />
        <el-table-column prop="diffQty" label="盘亏/盘盈" width="100">
          <template #default="scope">
            <span 
              v-if="scope.row.diffQty !== null && scope.row.diffQty !== undefined && scope.row.diffQty !== 0"
              :style="{
                color: scope.row.diffQty > 0 ? '#67c23a' : '#f56c6c',
                fontWeight: 'bold'
              }"
            >
              {{ scope.row.diffQty > 0 ? '+' + scope.row.diffQty : scope.row.diffQty }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="breakage" label="报损数量" width="100">
          <template #default="scope">
            {{ scope.row.breakage || 0 }}
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container" style="margin-top: 16px; text-align: right;">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getTaskDetailByGroup, getcountTaskDetail } from '@/api/Inventory/taskDetailGroup';

const inventoryTaskDetail = ref({});
const route = useRoute();
const router = useRouter();
const taskNum = ref('');
const count = ref(0);

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(10);
const allTaskDetailList = ref([]);

// 计算当前页数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return allTaskDetailList.value.slice(start, end);
});

// 计算总数
const total = computed(() => allTaskDetailList.value.length);

// 格式化日期
function formatDate(timestamp) {
  if (!timestamp) return '-';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    1: '待盘点',
    2: '盘点中',
    3: '待调整',
    4: '已完成',
    5: '已作废'
  };
  return statusMap[status] || '-';
}

// 获取库区名称列表
function getWarehouseNames() {
  if (!inventoryTaskDetail.value?.warehouseList || inventoryTaskDetail.value.warehouseList.length === 0) {
    return '-';
  }
  return inventoryTaskDetail.value.warehouseList.map(warehouse => warehouse.name).join('、');
}

// 返回上一页
function goBack() {
  history.back();
}

// 获取盘点任务详情
async function init() {
  const res = await getTaskDetailByGroup(taskNum.value);
  if (res.code == 200) {
    inventoryTaskDetail.value = res.data;
    // 从分组数据中提取所有明细
    extractAllTaskDetails();
  }
}

// 从分组数据中提取所有明细
function extractAllTaskDetails() {
  const allDetails = [];
  if (inventoryTaskDetail.value?.warehouseList) {
    inventoryTaskDetail.value.warehouseList.forEach(warehouse => {
      if (warehouse.locationDTOList) {
        warehouse.locationDTOList.forEach(location => {
          if (location.taskDetailDTOList) {
            location.taskDetailDTOList.forEach(detail => {
              allDetails.push({
                ...detail,
                warehouseName: warehouse.name,
                locationName: location.location
              });
            });
          }
        });
      }
    });
  }
  allTaskDetailList.value = allDetails;
}

// 获取盘点任务物品总数
async function countGoods() {
  const res = await getcountTaskDetail(taskNum.value);
  if (res.code == 200) {
    count.value = res.data;
  }
}

// 分页变化处理
function handlePageChange(val) {
  currentPage.value = val;
}

// 切换到分组展示
function switchToGroup() {
  router.push({ name: '盘点任务详情(分组展示)', query: { code: taskNum.value } });
}

// 获取路由参数
onMounted(() => {
  const code = route.query.code;
  if (code) {
    taskNum.value = code;
    init();
    countGoods();
  }
});
</script>

<style scoped>
.detail-bg {
  background: #fff;
  min-height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0 0 32px 0;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  font-size: 14px;
  color: #409eff;
}

.info-card {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.value {
  font-size: 14px;
  color: #303133;
  font-weight: bold;
}

.detail-card {
  margin-top: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
</style>